/**
 * 仓库管理日期处理工具函数
 * 统一处理仓库相关业务的日期格式化和计算
 */

/**
 * 获取当前日期
 * @returns {string} 格式：YYYY-MM-DD
 */
export function getCurrentDate() {
  const date = new Date();
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(date.getDate()).padStart(2, "0")}`;
}

/**
 * 获取当前日期时间
 * @returns {string} 格式：YYYY-MM-DD HH:mm:ss
 */
export function getCurrentDateTime() {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/**
 * 格式化日期
 * @param {Date|string} date 日期对象或字符串
 * @returns {string} 格式：YYYY-MM-DD
 */
export function formatDate(date) {
  if (!date) return "";
  const d = new Date(date);
  if (isNaN(d.getTime())) return "";

  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(d.getDate()).padStart(2, "0")}`;
}

/**
 * 格式化日期时间 (包含时分秒)
 * @param {Date|string} date 日期对象或字符串
 * @param {string} type 类型：'start' 或 'end'
 * @returns {string} 格式：YYYY-MM-DD HH:mm:ss
 */
export function formatDateTime(date, type = "start") {
  if (!date) return "";
  const d = new Date(date);
  if (isNaN(d.getTime())) return "";

  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  const hours = type === "start" ? "00" : "23";
  const minutes = type === "start" ? "00" : "59";
  const seconds = type === "start" ? "00" : "59";

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/**
 * 获取时间范围
 * @param {string} timeRange 时间范围类型：'today', 'week', 'month', 'yesterday', 'tomorrow'
 * @returns {Object} 包含startTime和endTime的对象
 */
export function getTimeRange(timeRange) {
  const now = new Date();
  let startDateTime, endDateTime;

  switch (timeRange) {
    case "today":
      // 当日：开始时间0点0分0秒，结束时间23点59分59秒
      startDateTime = formatDateTime(now, "start");
      endDateTime = formatDateTime(now, "end");
      break;
    case "yesterday":
      // 昨日：开始时间昨日0点0分0秒，结束时间昨日23点59分59秒
      const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
      startDateTime = formatDateTime(yesterday, "start");
      endDateTime = formatDateTime(yesterday, "end");
      break;
    case "tomorrow":
      // 明日：开始时间明日0点0分0秒，结束时间明日23点59分59秒
      const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000);
      startDateTime = formatDateTime(tomorrow, "start");
      endDateTime = formatDateTime(tomorrow, "end");
      break;
    case "week":
      // 本周：周一0点到当前时间
      const weekStart = new Date(now.setDate(now.getDate() - now.getDay()));
      startDateTime = formatDateTime(weekStart, "start");
      endDateTime = formatDateTime(new Date(), "end");
      break;
    case "month":
      // 本月：1号0点到月末23点59分59秒
      const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
      const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      startDateTime = formatDateTime(monthStart, "start");
      endDateTime = formatDateTime(monthEnd, "end");
      break;
    default:
      // 默认今日
      startDateTime = formatDateTime(now, "start");
      endDateTime = formatDateTime(now, "end");
  }

  return {
    startTime: startDateTime,
    endTime: endDateTime,
  };
}

/**
 * 更新日期范围 - 通用版本
 * @param {string} filter 时间筛选器类型：'today', 'week', 'month', 'yesterday', 'tomorrow'
 * @param {Object} options 可选参数对象
 * @param {Function} options.callback 回调函数，接收{startDate, endDate}参数
 * @param {Object} options.context 上下文对象（如Vue组件实例）
 * @param {string} options.startParam 开始日期参数名，默认为'startDate'
 * @param {string} options.endParam 结束日期参数名，默认为'endDate'
 * @returns {Object} 返回包含startDate和endDate的对象
 */
export function updateDateRange(filter, options = {}) {
  const today = new Date();
  let startDate, endDate;

  switch (filter) {
    case "today":
      // 当日：开始时间为0分0秒，结束时间为59分59秒
      const startOfDay = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate(),
        0,
        0,
        0
      );
      const endOfDay = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate(),
        23,
        59,
        59
      );
      startDate = formatDateTime(startOfDay, "start");
      endDate = formatDateTime(endOfDay, "end");
      break;
    case "yesterday":
      // 昨日：开始时间为昨日0分0秒，结束时间为昨日59分59秒
      const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
      const startOfYesterday = new Date(
        yesterday.getFullYear(),
        yesterday.getMonth(),
        yesterday.getDate(),
        0,
        0,
        0
      );
      const endOfYesterday = new Date(
        yesterday.getFullYear(),
        yesterday.getMonth(),
        yesterday.getDate(),
        23,
        59,
        59
      );
      startDate = formatDateTime(startOfYesterday, "start");
      endDate = formatDateTime(endOfYesterday, "end");
      break;
    case "tomorrow":
      // 明日：开始时间为明日0分0秒，结束时间为明日59分59秒
      const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
      const startOfTomorrow = new Date(
        tomorrow.getFullYear(),
        tomorrow.getMonth(),
        tomorrow.getDate(),
        0,
        0,
        0
      );
      const endOfTomorrow = new Date(
        tomorrow.getFullYear(),
        tomorrow.getMonth(),
        tomorrow.getDate(),
        23,
        59,
        59
      );
      startDate = formatDateTime(startOfTomorrow, "start");
      endDate = formatDateTime(endOfTomorrow, "end");
      break;
    case "week":
      const weekAgo = new Date(today.getTime() - 6 * 24 * 60 * 60 * 1000);
      startDate = formatDateTime(weekAgo, "start");
      endDate = formatDateTime(today, "end");
      break;
    case "month":
      const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
      const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
      startDate = formatDateTime(firstDay, "start");
      endDate = formatDateTime(lastDay, "end");
      break;
    default:
      startDate = formatDateTime(today, "start");
      endDate = formatDateTime(today, "end");
  }

  const result = { startDate, endDate };

  // 如果有回调函数，执行回调
  if (options.callback && typeof options.callback === "function") {
    options.callback(result);
  }

  // 如果有上下文对象和参数名，更新上下文对象的属性
  if (options.context) {
    const startParam = options.startParam || "startDate";
    const endParam = options.endParam || "endDate";

    if (options.context[startParam] !== undefined) {
      options.context[startParam] = startDate;
    }
    if (options.context[endParam] !== undefined) {
      options.context[endParam] = endDate;
    }
  }
  return result;
}

/**
 * 计算日期差值
 * @param {Date|string} startDate 开始日期
 * @param {Date|string} endDate 结束日期
 * @returns {number} 天数差值
 */
export function getDateDiff(startDate, endDate) {
  const start = new Date(startDate);
  const end = new Date(endDate);

  if (isNaN(start.getTime()) || isNaN(end.getTime())) return 0;

  const diffTime = Math.abs(end - start);
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  return diffDays;
}

/**
 * 添加天数
 * @param {Date|string} date 原始日期
 * @param {number} days 要添加的天数
 * @returns {Date} 新日期
 */
export function addDays(date, days) {
  const d = new Date(date);
  if (isNaN(d.getTime())) return new Date();

  d.setDate(d.getDate() + days);
  return d;
}

/**
 * 获取月份第一天和最后一天
 * @param {Date|string} date 日期
 * @returns {Object} 包含firstDay和lastDay的对象
 */
export function getMonthRange(date) {
  const d = new Date(date);
  if (isNaN(d.getTime())) return { firstDay: "", lastDay: "" };

  const firstDay = new Date(d.getFullYear(), d.getMonth(), 1);
  const lastDay = new Date(d.getFullYear(), d.getMonth() + 1, 0);

  return {
    firstDay: formatDate(firstDay),
    lastDay: formatDate(lastDay),
  };
}
//增加格式化到时分秒的函数

/**
 * 格式化时间戳到年月日时分秒格式
 * @param {number} timestamp 毫秒级时间戳
 * @param {string} format 格式化字符串，默认"yyyy-MM-dd HH:mm:ss"
 * @returns {string} 格式化后的时间字符串
 * @example
 * formateTime(1762776021000) // "2025-11-10 20:00:21"
 * formateTime(1762776021000, "HH:mm:ss") // "20:00:21"
 * formateTime(1762776021000, "yyyy-MM-dd") // "2025-11-10"
 */
export function formateTime(timestamp, format = "yyyy-MM-dd HH:mm:ss") {
  if (!timestamp || typeof timestamp !== "number") return "";

  const d = new Date(timestamp);
  if (isNaN(d.getTime())) return "";

  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  const hour = String(d.getHours()).padStart(2, "0");
  const minute = String(d.getMinutes()).padStart(2, "0");
  const second = String(d.getSeconds()).padStart(2, "0");

  return format
    .replace("yyyy", year)
    .replace("MM", month)
    .replace("dd", day)
    .replace("HH", hour)
    .replace("mm", minute)
    .replace("ss", second);
}

/**
 * 日期处理工具API命名空间
 * 统一封装所有日期相关函数
 */
export const dateHelperApi = {
  getCurrentDate,
  getCurrentDateTime,
  formatDate,
  formatDateTime,
  getTimeRange,
  updateDateRange,
  getDateDiff,
  addDays,
  getMonthRange,
  formateTime,
};

export default dateHelperApi;
